import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from '@/services/api'
import { ElMessage } from 'element-plus'

const app = createApp(App)

app.use(ElementPlus)

axios.interceptors.request.use(config => {
  const token = store.state.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

axios.interceptors.response.use(
  response => {
    // 检查响应数据是否符合 {data: "", result: "login_exception"}
    if (response.data && response.data.result === 'login_exception') {
      // 跳转到登录页面
      router.push('/login')
      ElMessage.error(response.data.data || '登录异常')

      return Promise.reject(new Error('登录异常'))
    }
    if (response.data && response.data.result === 'unauth') {
      // 显示无权限提示
      ElMessage.error(response.data.data || '无权限访问')
      return Promise.reject(new Error(response.data.data || '无权限访问'))
    }
    // 返回响应数据
    return response
  },
  error => {
    router.push('/login')
    
    return Promise.reject(error)
  }
)

app.use(router)
app.use(store)
app.mount('#app')